//
//  HMMainTabBarController.swift
//  iOSWeibo11
//
//  Created by Apple on 16/7/18.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit

class HMMainTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // 设置tabbar的tintClor, 使用normal的图片改变颜色,文字颜色和图片颜色一样的时候
//        self.tabBar.tintColor = UIColor.orangeColor()
        
        // 设置自定义tabBar
        let mainTabBar = HMMainTabBar()
        
        // 定义和传递闭包
        mainTabBar.composeCallback = { () -> Void in
            
            if HMUserAccountViewModel.sharedUserAccountViewModel.userLogin {
                // 弹出发微博界面
                let composeVC = HMComposeViewController()
                
                self.presentViewController(UINavigationController(rootViewController: composeVC), animated: true, completion: nil)
            } else {
                // 弹出登录界面
                let oauthVC = HMOauthViewController()
                
                self.presentViewController(UINavigationController(rootViewController: oauthVC), animated: true, completion: nil)
            }
        }
        
        // 设置tabbarVC的tabBar
        // = 直接赋值, get-only 就不能直接赋值
//        self.tabBar = mainTabBar
        // 间接赋值, KVC
        self.setValue(mainTabBar, forKey: "tabBar")

        addChildViewControllers()
    }

    /**
     添加所有子控制器
     */
    func addChildViewControllers() {
        // 添加子控制器
        // 首页
        let homeVC = HMHomeTableViewController()
        addChildViewController(homeVC, title: "首页", imageName: "tabbar_home")
        
        // 消息
        let messageVC = HMMessageTableViewController()
        addChildViewController(messageVC, title: "消息", imageName: "tabbar_message_center")
        
        // 发现
        let discoveryVC = HMDiscoveryTableViewController()
        addChildViewController(discoveryVC, title: "发现", imageName: "tabbar_discover")
        
        // 我
        let profileVC = HMProfileTableViewController()
        addChildViewController(profileVC, title: "我", imageName: "tabbar_profile")
    }
    
    /**
     添加子控制器,会包装导航控制器
     
     - parameter controller: 控制器
     - parameter title:      title
     - parameter imageName:  图片名称
     */
    func addChildViewController(controller: UIViewController, title: String, imageName: String) {
        // 设置标题和图片
        controller.title = title
        
        // 设置选中时字体颜色
        controller.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.orangeColor()], forState: UIControlState.Selected)
        
        controller.tabBarItem.image = UIImage(named: imageName)
        
        // 拼接选中图片的名称
        let selectedImageName = imageName + "_selected"
        // 设置选中的图片
        controller.tabBarItem.selectedImage = UIImage(named: selectedImageName)?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
        
        self.addChildViewController(UINavigationController(rootViewController: controller))
    }
}
